<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
    <FormItem label="标题" prop="title">
      <Input v-model="formValidate.title" placeholder="请输入物品名称" />
    </FormItem>
    <Row>
      <Col span="8">
        <FormItem label="类别" prop="kind">
          <Cascader :data="kindData" 
          v-model="formValidate.kind" 
          style="width: 200px" 
          :disabled="this.$route.query.type?true:false"/>
        </FormItem>
      </Col>

      <Col span="8">
        <FormItem label="定价" prop="price">
          <InputNumber
            :max="99999"
            :min="1"
            :step="0.1"
            v-model="formValidate.price"
            :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            style="width: 150px"
          />
        </FormItem>
      </Col>
      <Col span="8">
        <FormItem label="数量" prop="amount">
          <InputNumber :max="9999" :min="1" v-model="formValidate.amount" style="width: 150px"></InputNumber>
        </FormItem>
      </Col>
    </Row>

    <FormItem label="简介" prop="desc">
      <Input
        v-model="formValidate.desc"
        type="textarea"
        :autosize="{minRows: 3,maxRows: 5}"
        placeholder="介绍一下宝贝吧~"
      />
    </FormItem>
    <FormItem label="图片" prop="file">
      <Upload
        multiple
        action="#"
        type="drag"
        :format="['jpg', 'png','jpeg']"
        :before-upload="beforeUpload"
        :max-size="5120"
      >
        <div style="padding: 20px 0" v-if="uploadToggle">
          <Icon type="ios-checkmark-circle-outline" size="52" style="color: #2ecc71"></Icon>
          <p>图片：{{this.formValidate.file.name}}</p>
        </div>
        <div style="padding: 20px 0" v-else>
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p v-if="this.formValidate.file && this.$route.query.type">
            <img :src="this.formValidate.file.name" style="width: 200px" />
          </p>
          <p v-else-if="this.formValidate.file">{{this.formValidate.file.name}}</p>
          <p v-else>请上传一张封面图(尺寸为1:1)</p>
        </div>
      </Upload>
    </FormItem>

    <FormItem>
      <Button :loading="loadingStatus" type="primary" @click="handleSubmit('formValidate')">发布</Button>
      <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置表单</Button>
    </FormItem>
  </Form>
</template>

<script>
import { getBasicInfo } from "../../utils/mixin";

export default {
  name: "publish-goods",
  mixins: [getBasicInfo],
  data() {
    return {
      uploadToggle: false,
      loadingStatus: false,
      formValidate: {
        title: "",
        kind: [],
        price: 0,
        amount: 0,
        desc: "",
        file: ""
      },
      ruleValidate: {
        title: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "blur"
          },
          {
            type: "string",
            min: 6,
            message: "请填写至少6个字",
            trigger: "blur"
          }
        ],
        kind: [
          {
            required: true,
            message: "种类不能为空"
          }
        ],
        price: [
          {
            required: true,
            message: "价格不能为空",
            type: "number"
          }
        ],
        amount: [
          {
            required: true,
            message: "请填写库存数量",
            type: "number"
          }
        ],
        desc: [
          {
            required: true,
            message: "请输入商品简介",
            trigger: "blur"
          },
          {
            type: "string",
            min: 20,
            message: "请填写至少20个字",
            trigger: "blur"
          }
        ],
        file: [
          {
            required: true,
            message: "请至少上传一张实物图"
          }
        ]
      },
      kindData: []
    };
  },
  mounted() {
    this.axios
      .get("/api/category")
      .then(res => (this.kindData = res.data))
      .catch(error => console.log("error :", error));
    if (this.$route.query.type == "goods_edit")
      this.axios
        .get(`/api/goods?goods=${this.$route.query.goods_id}`)
        .then(res => {
          let goods = res.data;
          this.formValidate.title = goods.title;
          this.formValidate.desc = goods.desc;
          this.formValidate.price = parseInt(goods.price);
          this.formValidate.amount = goods.amount;
          this.formValidate.file = { name: goods.image_src };
          this.formValidate.kind = [goods.kind.category_id, goods.kind.id];
        });
  },
  methods: {
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.$route.query.type) {
            this.axios
              .post("/api/goods", {
                id: this.$route.query.goods_id,
                title: this.formValidate.title,
                desc: this.formValidate.desc,
                price: this.formValidate.price,
                amount: this.formValidate.amount
              })
              .then(res => {
                console.log('res.data :>> ', res.data);
                this.$Notice.success({
                  title: "保存成功"
                });
                this.$router.push(`/user/${this.getUid}/goods_management?type=goods`);
              })
              .catch(error =>
                this.$Notice.error({
                  title: "保存失败",
                  desc: error
                })
              );
          } else {
            this.loadingStatus = true;
            let newFormData = new FormData();
            this.formValidate.kind = this.formValidate.kind[1];
            for (let key in this.formValidate) {
              newFormData.append(key, this.formValidate[key]);
            }
            newFormData.append('cid',this.getCid);
            this.axios
              .post("/api/goods", newFormData, {
                headers: {
                  "Content-Type": "multipart/form-data"
                }
              })
              .then(res => {
                this.uploadToggle = true;
                this.loadingStatus = false;
                this.$Notice.success({
                  title: "添加商品成功"
                });
                this.handleReset('formValidate');
              })
              .catch(error =>
                this.$Notice.error({
                  title: "网络连接失败",
                  desc: error
                })
              );
          }
        } else this.$Message.error("信息填写不正确！请更正后重新提交");
      });
    },
    beforeUpload(file) {
      this.formValidate.file = file;
      return this.uploadToggle;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
      this.uploadToggle = false;
    }
  }
};
</script>
